package concept.misc;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;

public class BetterProgrammerTask {

    public static int getClosestToZero(int[] a) {
        /*
          Please implement this method to
          return the number in the array that is closest to zero.
          If there are two equally close to zero elements like 2 and -2
          - consider the positive element to be "closer" to zero.
         */
    	if(a==null || a.length==0)
    	{
    		throw new RuntimeException("Array cannot be null or empty");
    	}
    	else
    	{
    		NavigableSet<Integer> iSet = new TreeSet<Integer>();
    		List<Integer> iList = new ArrayList<Integer>();
    		for(int i:a)
    		{
    			iSet.add(i);
    			iList.add(i);
    		}
    		int closestPositive = iSet.higher(0);
    		int closestNegative = iSet.lower(0);
    		if(Math.abs(closestNegative) < Math.abs(closestPositive))
    		{
    			return iList.indexOf(closestNegative);
    		}
    		else
    		{
    			return iList.indexOf(closestPositive);
    		}
    	}
    }
    
    public static int getRequiredNumberOfBits(int N) {
        /*
          Please implement this method to
          return the number of bits which is just enough to store any integer from 0 to N-1 inclusively
          for any int N > 0
          Example: to store 5 integers from 0 to 4 you need 3 bits: 000, 001, 010, 011, 100 and 101
        */
    	List<Integer> remainings = new ArrayList<Integer>();
    	N--;
    	for(int r=N%2; (N/=2) >= 1;)
    	{
    		remainings.add(r);
    	}
    	
    	return remainings.size()+1;
    }
    
    public static String getBinaryFromDecimal(int dec)
    {
    	StringBuilder remainings = new StringBuilder();
    	for(int r;(r=dec%2)<2 && (dec/=2) >= 1;)
    	{
    		remainings.append(r);
    	}
    	remainings.append(1);
    	return remainings.reverse().toString();
    }
    
    public static void main(String...strings)
    {
    	/*int[] a = {-5, -4, -3, -1, 2, 7};
    	System.out.println(getClosestToZero(a));
    	System.out.println(getRequiredNumberOfBits(1));*/
    	System.out.println(getBinaryFromDecimal(57));
    }
}